﻿package com.valorin.arenas;

import static com.valorin.Dantiao.getInstance;
import static com.valorin.dan.ExpChange.changeExp;
import static com.valorin.arenas.ArenasManager.busyArenasName;
import static com.valorin.configuration.DataFile.areas;
import static com.valorin.configuration.DataFile.pd;
import static com.valorin.configuration.DataFile.savepd;
import static com.valorin.configuration.languagefile.MessageSender.gm;
import static com.valorin.configuration.languagefile.MessageSender.sm;
import static com.valorin.configuration.languagefile.MessageSender.sml;

import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import com.valorin.Dantiao;
import com.valorin.api.event.ArenaEventAbs;
import com.valorin.api.event.arena.ArenaDrawFinishEvent;
import com.valorin.api.event.arena.ArenaFinishEvent;
import com.valorin.dan.CommonDan;
import com.valorin.dan.DansHandler;
import com.valorin.dan.type.Common;
import com.valorin.effect.WinFirework;
import com.valorin.energy.Energy;
import com.valorin.teleport.ToLobby;
import com.valorin.teleport.ToLogLocation;

public class Finisher {
  public static void normalEnd(String name,String winner,String loser,boolean isDraw) {//正常结束
    Arena arena = getInstance().getArenasHandler().getArena(name);
    if (arena == null) {return;}
	if (!arena.getEnable()) {return;}
	
    Player w = Bukkit.getPlayerExact(winner);
    Player l = Bukkit.getPlayerExact(loser);
    
    if (w.isDead()) { w.spigot().respawn(); }
    if (l != null)
    {
      if (l.isDead()) { l.spigot().respawn(); }
    }
	
	w.setHealth(w.getMaxHealth());
	w.setFoodLevel(20);
	if (l != null) {
      l.setHealth(l.getMaxHealth());
      l.setFoodLevel(20);
	}
	
	Energy e = getInstance().getEnergy();
	if (e.getEnable()) {
	  e.setEnergy(winner, e.getEnergy(winner) - e.getNeed());
	  e.setEnergy(loser, e.getEnergy(loser) - e.getNeed());
	}
	
	RecordData.record(name, winner, loser, isDraw);
	if (!isDraw) {//正常
	    boolean b1 = arena.isp1(winner);
	    int winnerExp;
	    int loserExp;
	    int maxExp = getInstance().getConfig().getInt("Rewards.MaxExp");
	    if (arena.getExp(b1) > maxExp) {
	      winnerExp = maxExp;
	    } else {
	      winnerExp = arena.getExp(b1);
	    }
        winnerExp = winnerExp + getInstance().getConfig().getInt("Rewards.WinExp");
	    loserExp = (int)arena.getExp(b1)/3;
	
	    changeExp(w,pd.getInt(winner+".Exp")+winnerExp);
		
		int firstLevelExp;
		DansHandler dh = getInstance().getDansHandler();
		List<CommonDan> danList = dh.getDanList();
		boolean isUseDefault = false;
		if (danList != null) {
		  if (danList.size() == 0) {
			isUseDefault = true;
		  }
		} else {
		  isUseDefault = true;
		}
		if (isUseDefault)
		{
		  firstLevelExp = 50;
		} else {
		  firstLevelExp = danList.get(0).getExp();
		}
			
		int loserExpShow = loserExp;
		int loserExpNow = pd.getInt(loser+".Exp");
		if (loserExpNow - loserExp > firstLevelExp) {
		  changeExp(l,loserExpNow-loserExp); //正常扣除经验
		} else {
		  if (loserExpNow > firstLevelExp) {
			loserExpShow = loserExpNow - firstLevelExp;
			changeExp(l,firstLevelExp); //设置为保底经验
		  } else {
			loserExpShow = 0; //不扣经验
		  }
		}
		savepd();
	    sml("&7============================================================| |                    &b比赛结束！|          &7恭喜获得了胜利，期待你下一次更加精彩得表现！|          &7同时获得了 &a{exp} &7经验| |&7============================================================"
		,w,"exp",new String[]{""+winnerExp});
	    if (l != null) {
	      sml("&7============================================================| |                    &b比赛结束！|          &7你没有获胜，不要灰心，再接再厉！|          &7同时损失了 &c{exp} &7经验| |&7============================================================"
		  ,l,"exp",new String[]{""+loserExpShow});
	    }
	    getInstance().getHD().load(0); //重载全息排行榜
	    String arenaName = areas.getString("Arenas."+arena.getName()+".Name");
		if (arenaName == null) {
		  arenaName = "";
		}
	    Bukkit.broadcastMessage(
				gm("&b[战报]: &7玩家 &e{winner} &7在单挑赛场&r{arenaname}&r&7上以 &6{time}秒 &7击败玩家 &e{loser}",null,"winner arenaname time loser",new String[]{winner,arenaName,arena.getTime()+"",loser}));
	} else { //平局
		int drawExp = getInstance().getConfig().getInt("Rewards.DrawExp");
		changeExp(w,pd.getInt(winner+".Exp")+drawExp);
		changeExp(l,pd.getInt(loser+".Exp")+drawExp);
		savepd();
		sml("&7============================================================| |                    &b比赛结束！|          &7比赛超时！未决出胜负，判定为平局！|          &7同时获得了 &a{exp} &7经验| |&7============================================================"
		,w,"exp",new String[]{""+drawExp});
		if (l != null) {
		  sml("&7============================================================| |                    &b比赛结束！|          &7比赛超时！未决出胜负，判定为平局！|          &7同时获得了 &a{exp} &7经验| |&7============================================================"
		  ,l,"exp",new String[]{""+drawExp});
		}
		new BukkitRunnable() {
		  public void run() {
		    Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "/dt hd refresh");
		  }
		}.runTask(Dantiao.getInstance());
		String arenaDisplayName = areas.getString("Arenas."+arena.getName()+".Name");
		if (arenaDisplayName == null) {
		  arenaDisplayName = "";
		}
		Bukkit.broadcastMessage(
				gm("&b[战报]: &7玩家 &e{p1} &7与 &e{p2} &7在单挑赛场&r{arenaname}&r&7上打成平手，实为精妙！",null,"p1 arenaname p2",new String[]{winner,arenaDisplayName,loser}));
	}
	
	DansHandler dh = getInstance().getDansHandler();
	dh.refreshPlayerDan(winner);
	dh.refreshPlayerDan(loser);
	if (arena.getDan(arena.isp1(winner)) instanceof Common) {
	  List<CommonDan> danList = dh.getDanList();
	  for (int i = 0;i < danList.size();i++) {
	    if (danList.get(i).getDanName().equals(arena.getDan(arena.isp1(winner)).getDanName())) {
	      int danNumBefore = arena.getDan(arena.isp1(winner)).getNum();
	      int danNumNow = dh.getPlayerDan(winner).getNum();
	      if (danNumNow > danNumBefore) {
		    Bukkit.broadcastMessage(
				gm("&a[恭喜]: &7玩家 &e{player} &7的单挑段位成功升到了&r{dan}",null,"player dan",new String[]{winner,dh.getPlayerDan(winner).getDanName()}));
	      }
	      break;
	    }
	  }
	} else {
	  if (dh.getPlayerDan(winner) instanceof Common) {
		  Bukkit.broadcastMessage(
				gm("&a[恭喜]: &7玩家 &e{player} &7突破了无段位的身份，首次获得了段位：&r{dan}&7！祝TA在单挑战斗的路上越走越远！",null,"player dan",new String[]{winner,dh.getPlayerDan(winner).getDanName()}));
	  }
	}
	if (arena.getDan(arena.isp1(loser)) instanceof Common) {
	  List<CommonDan> danList = dh.getDanList();
	  for (int i = 0;i < danList.size();i++) {
		if (danList.get(i).getDanName().equals(arena.getDan(arena.isp1(winner)).getDanName())) {
	      int danNumBefore = arena.getDan(arena.isp1(loser)).getNum();
	      int danNumNow = dh.getPlayerDan(loser).getNum();
	      if (danNumNow > danNumBefore) {
		    Bukkit.broadcastMessage(
				gm("&a[恭喜]: &7玩家 &e{player} &7的单挑段位成功升到了&r{dan}",null,"player dan",new String[]{winner,dh.getPlayerDan(winner).getDanName()}));
	      }
	      break;
		}
	  }
	} else {
	  if (dh.getPlayerDan(loser) instanceof Common) {
		  Bukkit.broadcastMessage(
				gm("&a[恭喜]: &7玩家 &e{player} &7突破了无段位的身份，首次获得了段位：&r{dan}&7！祝TA在单挑战斗的路上越走越远！",null,"player dan",new String[]{loser,dh.getPlayerDan(loser).getDanName()}));
	  }
	}
	
	arena.setWatchersTeleport(true);
	List<String> watchers = arena.getWatchers();
	if (areas.getString("Dantiao-LobbyPoint.World") != null) {
      ToLobby.to(w);
	  ToLobby.to(l);
	  sm("&b已将你带回单挑大厅！",w);
	  if (l != null) {
	    sm("&b已将你带回单挑大厅！",l);
	  }
	  for (String watcher : watchers) {
		if (Bukkit.getPlayerExact(watcher) != null) {
		  ToLobby.to(Bukkit.getPlayerExact(watcher));
		  sm("&b已将你带回单挑大厅！",l);
		}
	  }
	} else {
	  Location winnerLocation = arena.getLoaction(arena.isp1(w.getName()));
	  Location loserLocation = arena.getLoaction(arena.isp1(l.getName()));
	  ToLogLocation.to(w,l,winnerLocation,loserLocation);
	  for (String watcher : watchers) {
		if (Bukkit.getPlayerExact(watcher) != null) {
		  sm("&b[报告] &7你所观战的竞技场上的比赛已结束，请自行传送回家...",Bukkit.getPlayerExact(watcher),false);
		}
	  }
	}//回到原处
	if (getInstance().getConfig().getBoolean("Rewards.Firework")) {
	  WinFirework.setFirework(w.getLocation());
	  sm("&a[v]WOW！服务器专门为你的获胜放了一朵烟花~",w);
	}
	
	arena.finish();
	busyArenasName.remove(arena.getName());//结算完毕，竞技场结束比赛
	getInstance().getDuelAmountData().add();

    ArenaEventAbs event;
    if (isDraw) {
      event = new ArenaDrawFinishEvent(w, l, arena);
    } else {
      event = new ArenaFinishEvent(w, l, arena);
    }
    Bukkit.getServer().getPluginManager().callEvent(event);
  }
  
  public static void compulsoryEnd(String name,Player finisher) {//强制结束，不予记录
	Arena arena = getInstance().getArenasHandler().getArena(name);
	if (arena == null) { 
		sm("&c[x]不存在的竞技场，请检查输入",finisher); return;}
	if (!arena.getEnable()) { 
		sm("&c[x]这个竞技场还没有比赛呢！",finisher); return;}
	
	Player p1 = Bukkit.getPlayerExact(arena.getp1());
	Player p2 = Bukkit.getPlayerExact(arena.getp2());
	
	arena.setWatchersTeleport(true);
	List<String> watchers = arena.getWatchers();
	if (areas.getString("Dantiao-LobbyPoint.World") != null) {
	  if (p1 != null) {
        ToLobby.to(p1);
	    sm("&b已将你带回单挑大厅！",p1);
	  }
	  if (p2 != null) {
		ToLobby.to(p2);
	    sm("&b已将你带回单挑大厅！",p2);
	  }
	  for (String watcher : watchers) {
		if (Bukkit.getPlayerExact(watcher) != null) {
		  ToLobby.to(Bukkit.getPlayerExact(watcher));
		  sm("&b已将你带回单挑大厅！",p2);
		}
	  }
	} else {
	  Location winnerLocation = arena.getLoaction(arena.isp1(p1.getName()));
	  Location loserLocation = arena.getLoaction(arena.isp1(p2.getName()));
	  ToLogLocation.to(p1,p2,winnerLocation,loserLocation);
	  for (String watcher : watchers) {
		if (Bukkit.getPlayerExact(watcher) != null) {
		  sm("&b[报告] &7你所观战的竞技场上的比赛已结束，请自行传送回家...",Bukkit.getPlayerExact(watcher));
		}
	  }
	}//回到原处
	
	arena.finish();
	sm("&b&l比赛被管理员强制结束！本局比赛不会被记录！",p1,p2);
	sm("&a[v]已强制停止",finisher);
	busyArenasName.remove(arena.getName());
  }
}
